package com.red.wood.module.eval.until;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 公用工具类
 * @author ycl
 * @date 2012-10-19下午05:04:20
 * @version 1.0
 */
public class CommonUtil {

	private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class);

	public static final String SUPERNAME = "superadmin";
	public static final String ISSMSOPEN = "isSmsOpen";//说明开启短信发送
	public static final String ISSMSSENDBY = "isSmsSendBy";//说明是短信平台发送
	public static final String SMSTool = "SMSTool";
	public static final String warningMessageEnabled = "warningMessageEnabled";

	public static String regExURl = "(http|https)://[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?";
	public static String regExQQNumber = "^[0-9]*$";
	public static String regExIP = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
			+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
	public static String regExNumber = "^[+-]?\\d+\\.?\\d*$";

	public static boolean isLegal(Object obj) {
		if (obj != null) {
			if (obj instanceof Collection<?>) {
				Collection<?> col = (Collection<?>) obj;
				if (!col.isEmpty()) {
					return true;
				}
			} else if (obj instanceof Number) {
				Number num = (Number) obj;
				if (num.doubleValue() > 0) {
					return true;
				}
			} else if (obj instanceof String) {
				String s = (String) obj;
				if (!s.trim().isEmpty()) {
					return true;
				}
			} else {
				return true;
			}
		}
		return false;
	}
	
	public static boolean isUrl(String url){
		if(StringUtils.isBlank(url)){
			return false;
		}
		return validation(url.trim(), regExURl);
	}
	
	/**
	 * 上传文件
	 * @param name 文件名（可为空）
	 * @param in 输入流 
	 * @param childPath 子目录名
	 * @author xdp
	 * @date 2013-11-21
	 */
	public static String uploadFile(String name, InputStream in, String rootPath, String childPath) {
		String filename = "";
		FileOutputStream out = null;
		try {
//			String rootPath = FileUtil.getResouseValue("uploadpath");
			if(childPath!=null && childPath.trim().length()>0){
				childPath = childPath.trim();
				if(!childPath.startsWith("/") && !childPath.startsWith("\\")){
					childPath = "/" + childPath;
				}
				rootPath += childPath;
			}
//			filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			UUID uuid=UUID.randomUUID();
			filename = uuid.toString();
			if (name != null && !name.trim().isEmpty()) {
				int i = name.indexOf(".");
				name = name.substring(i, name.length());
//				filename +=  "_" + name.trim();
			}
			File file = new File(rootPath);
			if (!file.exists() || !file.isDirectory()) {
				file.mkdirs();
			}
			byte[] bytes = new byte[10240];
		    out = new FileOutputStream(new File(file, filename));
			int count = 0;
			while ((count = in.read(bytes)) != -1) {
				out.write(bytes, 0, count);
			}
		} catch (IOException ie) {
			logger.error("读取文件异常", ie);
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(in);
		}
		return filename;
	}

	/**
	 * 下载文件
	 * @param name 文件名
	 * @param out 输出流
	 * @author ycl
	 * @date 2012-11-2
	 */
	public static void downloadFile(String name, OutputStream out, String rootPath) {
		FileInputStream in = null;
		try {
			if (name != null && !name.trim().isEmpty()) {
				name = name.trim();
				if(!name.startsWith("/") && !name.startsWith("\\")){
					name = "/" + name;
				}
//				String path = FileUtil.getResouseValue("uploadpath") + name;
				String path = rootPath + name;
				File file = new File(path);
				if (file.exists()) {
					in = new FileInputStream(file);
					byte[] bytes = new byte[10240];
					while (in.read(bytes) > 0) {
						out.write(bytes);
					}
				}
			}
		} catch (FileNotFoundException fe) {
			logger.error("找不到文件异常", fe);
		} catch (IOException ie) {
			logger.error("读取文件异常", ie);
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(in);
		}
	}

	/**
	 * 获取所有直接父级节点
	 * 
	 * 修改人：Eliaine 修改时间：2011-7-22 下午12:44:17 修改备注：
	 * 
	 * @param node
	 * @return
	 * @version
	 * 
	 */
	public static List<String> getAllHigherNodes(String node) {
		List<String> higherNodes = new ArrayList<String>();
		higherNodes.add(node);
		while (node.length() > 2) {
			node = node.substring(0, node.length() - 2);
			higherNodes.add(node);
		}
		return higherNodes;
	}
	
	public static boolean validation(String content, String regEx) {
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(content);
		return m.matches();
	}

	public static void writerToPage(String msg, HttpServletResponse response) {
		response.setContentType("text/json;charset=UTF-8");
		try {
			response.getWriter().write(msg);
		} catch (IOException e) {
			logger.error("向页面输出 json 异常", e);
		}
	}
}
